<template>
  <div class="book-detail-page">
    <div class="book-header">
      <div class="container">
        <div class="book-info-wrapper">
          <div class="book-cover">
            <div class="book-cover-placeholder" :style="{
              background: `linear-gradient(135deg, ${book.coverColors[0]} 0%, ${book.coverColors[1]} 100%)`
            }">
              <span class="book-cover-title">{{ book.title }}</span>
            </div>
          </div>
          <div class="book-info">
            <h1 class="book-title">{{ book.title }}</h1>
            <div class="book-meta">
              <router-link :to="`/author-page/${book.authorId}`" class="author-link">{{ book.author }}</router-link>
              <span class="separator">|</span>
              <span class="category">{{ book.category }}</span>
              <span class="separator">|</span>
              <span class="status" :class="{ 'completed': book.status === '已完结' }">{{ book.status }}</span>
            </div>
            <div class="book-rating">
              <span class="rating-score">{{ book.rating }}</span>
              <el-rate
                :value="book.rating"
                disabled
                text-color="#ff9900"
                score-template="{value}">
              </el-rate>
              <span class="rating-count">({{ book.ratingCount }}人评分)</span>
            </div>
            <div class="book-stats">
              <div class="stat-item">
                <div class="stat-value">{{ book.wordCount }}</div>
                <div class="stat-label">字数</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ book.views }}</div>
                <div class="stat-label">阅读</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ book.favorites }}</div>
                <div class="stat-label">收藏</div>
              </div>
            </div>
            <div class="book-desc">{{ book.desc }}</div>
            <div class="book-tags" v-if="book.tags && book.tags.length">
              <el-tag v-for="tag in book.tags" :key="tag" size="small" effect="plain" class="book-tag">{{ tag }}</el-tag>
            </div>
            <div class="book-actions">
              <el-button type="primary" @click="startReading">开始阅读</el-button>
              <el-button type="info" plain @click="addToBookshelf">加入书架</el-button>
              <el-button type="warning" plain @click="toggleFavorite">
                <i :class="isFavorite ? 'el-icon-star-on' : 'el-icon-star-off'"></i> 
                {{ isFavorite ? '已收藏' : '收藏' }}
              </el-button>
            </div>
            <div class="last-updated">
              <span>最近更新：</span>
              <span class="update-time">{{ book.updateTime }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="book-content container">
      <div class="chapter-list-section">
        <div class="section-header">
          <h2 class="section-title">章节列表</h2>
          <div class="chapter-controls">
            <el-button-group class="order-buttons">
              <el-button size="small" :type="chapterOrder === 'asc' ? 'primary' : ''" @click="toggleChapterOrder">正序</el-button>
              <el-button size="small" :type="chapterOrder === 'desc' ? 'primary' : ''" @click="toggleChapterOrder">倒序</el-button>
            </el-button-group>
            <el-input
              v-if="chapters.length > 0"
              class="jump-page-input"
              placeholder="跳转页"
              size="small"
              v-model="jumpPage"
              type="number"
              min="1"
              :max="totalPages"
              @keyup.enter.native="handleJumpPage"
            >
              <el-button slot="append" icon="el-icon-d-arrow-right" @click="handleJumpPage"></el-button>
            </el-input>
          </div>
        </div>
        <el-row :gutter="20" class="chapter-list">
          <el-col :xs="24" :sm="12" :md="8" v-for="(chapter, index) in displayedChapters" :key="index">
            <router-link :to="`/reader/${book.id}?chapter=${chapter.id}`" class="chapter-item">
              {{ chapter.title }}
            </router-link>
          </el-col>
        </el-row>
        <div class="pagination-wrapper">
          <el-pagination
            @current-change="handleChapterPageChange"
            :current-page.sync="currentChapterPage"
            :page-size="chapterPageSize"
            layout="prev, pager, next, total"
            :total="chapters.length"
            :disabled="chapters.length === 0">
          </el-pagination>
        </div>
      </div>
      
      <div class="comments-section mt-5">
        <div class="section-header">
          <h2 class="section-title">读者评论</h2>
          <div class="comments-count">共 {{ comments.length }} 条评论</div>
        </div>
        
        <div class="comment-form-wrapper">
          <div class="user-rating">
            <span class="rating-label">我的评分：</span>
            <el-rate v-model="userRating" show-text></el-rate>
          </div>
          <el-input
            type="textarea"
            :rows="4"
            placeholder="写下你的评论..."
            v-model="userComment"
            maxlength="500"
            show-word-limit
          ></el-input>
          <div class="form-actions">
            <el-button type="primary" @click="submitComment" :disabled="!userComment.trim()">发布评论</el-button>
          </div>
        </div>
        
        <div class="comments-list">
          <div v-for="(comment, index) in displayedComments" :key="index" class="comment-item">
            <div class="comment-user">
              <div class="user-avatar" :style="{
                background: `linear-gradient(135deg, ${comment.avatarColors[0]} 0%, ${comment.avatarColors[1]} 100%)`
              }">{{ comment.username.charAt(0) }}</div>
              <div class="user-info">
                <div class="username">{{ comment.username }}</div>
                <div class="comment-rating">
                  <el-rate :value="comment.rating" disabled text-color="#ff9900" size="small"></el-rate>
                </div>
              </div>
            </div>
            <div class="comment-content">{{ comment.content }}</div>
            <div class="comment-footer">
              <span class="comment-time">{{ comment.time }}</span>
              <div class="comment-actions">
                <el-button type="text" size="mini" @click="likeComment(index)">
                  <i :class="comment.liked ? 'el-icon-star-on' : 'el-icon-star-off'"></i> 
                  点赞({{ comment.likes }})
                </el-button>
                <el-button type="text" size="mini" @click="replyComment(index)">回复</el-button>
              </div>
            </div>
          </div>
        </div>
        
        <div class="view-more-comments">
          <el-button v-if="hasMoreComments" type="text" @click="loadMoreComments">
            查看更多评论 <i class="el-icon-arrow-down"></i>
          </el-button>
          <el-button v-else-if="comments.length > 3 && displayCommentCount > 3" type="text" @click="collapseComments">
            收起评论 <i class="el-icon-arrow-up"></i>
          </el-button>
        </div>
      </div>
      
      <div class="similar-books-section mt-5">
        <div class="section-header">
          <h2 class="section-title">相似推荐</h2>
        </div>
        <el-row :gutter="20" class="mt-3">
          <el-col :xs="12" :sm="8" :md="6" :lg="4" v-for="(book, index) in similarBooks" :key="index">
            <div class="book-item">
              <div class="book-cover-wrapper">
                <div class="book-cover-placeholder" :style="{
                  background: `linear-gradient(135deg, ${book.coverColors[0]} 0%, ${book.coverColors[1]} 100%)`
                }">
                  <span class="book-cover-title">{{ book.title }}</span>
                </div>
              </div>
              <div class="book-info mt-2">
                <div class="book-title text-ellipsis">{{ book.title }}</div>
                <div class="book-author text-ellipsis text-secondary mt-1">{{ book.author }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BookDetail',
  data() {
    return {
      book: {
        id: null,
        title: '加载中...',
        author: '加载中...',
        authorId: 1,
        category: '加载中...',
        status: '连载中',
        wordCount: '0',
        views: '0',
        favorites: '0',
        desc: '加载中...',
        updateTime: '加载中...',
        rating: 0,
        ratingCount: 0,
        tags: [],
        coverColors: ['#f0f0f0', '#e0e0e0']
      },
      chapters: [],
      similarBooks: [],
      comments: [],
      userComment: '',
      userRating: 0,
      isFavorite: false,
      chapterOrder: 'asc',
      currentChapterPage: 1,
      chapterPageSize: 12,
      displayCommentCount: 3,
      jumpPage: ''
    }
  },
  computed: {
    displayedChapters() {
      const sortedChapters = [...this.chapters];
      if (this.chapterOrder === 'desc') {
        sortedChapters.reverse();
      }
      
      const start = (this.currentChapterPage - 1) * this.chapterPageSize;
      const end = start + this.chapterPageSize;
      
      return sortedChapters.slice(start, end);
    },
    displayedComments() {
      return this.comments.slice(0, this.displayCommentCount);
    },
    hasMoreComments() {
      return this.comments.length > this.displayCommentCount;
    },
    totalPages() {
      return Math.ceil(this.chapters.length / this.chapterPageSize);
    }
  },
  created() {
    const bookId = this.$route.params.id;
    this.fetchBookDetail(bookId);
    this.fetchChapters(bookId);
    this.fetchSimilarBooks(bookId);
    this.fetchComments(bookId);
  },
  methods: {
    fetchBookDetail(bookId) {
      setTimeout(() => {
        this.book = {
          id: bookId,
          title: '沧元图',
          author: '我吃西红柿',
          authorId: 1,
          category: '东方玄幻',
          status: '连载中',
          wordCount: '300万',
          views: '1250万',
          favorites: '35万',
          desc: '一个修真文明开辟了通往其他宇宙的通道，这可能是一场灾难，也可能蕴藏着无限的机遇。吴青当年很不幸，但如今他已长大，而且拥有了那个可以摧毁世界的力量...',
          updateTime: '2023-03-04 12:30',
          rating: 4.5,
          ratingCount: 2834,
          tags: ['修真', '热血', '冒险', '穿越', '机遇'],
          coverColors: ['#3E5151', '#DECBA4']
        };
      }, 500);
    },
    // eslint-disable-next-line no-unused-vars
    fetchChapters(_bookId) {
      setTimeout(() => {
        this.chapters = Array.from({ length: 50 }, (_, i) => ({
          id: `${_bookId}_${i + 1}`,
          title: `第${i + 1}章 ${['命运的转折', '神秘力量', '初入修真', '修炼之路', '第一次历练', 
                 '奇遇', '古老的秘密', '强者云集', '危机四伏', '突破', 
                 '新的开始', '宗门大比', '意外相逢', '强敌来袭', '生死一线',
                 '巧妙脱险', '机缘巧合', '神秘老者', '宝物现世', '争夺之战',
                 '古怪传承', '瓶颈突破', '世界真相', '天道奥秘', '万古传说'][i % 25]}`
        }));
      }, 600);
    },
    // eslint-disable-next-line no-unused-vars
    fetchSimilarBooks(_bookId) {
      setTimeout(() => {
        this.similarBooks = [
          { id: `${_bookId}_s1`, title: '仙侠世界', author: '梦幻仙尊', coverColors: ['#4DA0B0', '#D39D38'] },
          { id: `${_bookId}_s2`, title: '九域仙主', author: '神话传说', coverColors: ['#5614B0', '#DBD65C'] },
          { id: `${_bookId}_s3`, title: '诸天万界', author: '纵横天下', coverColors: ['#2A5470', '#4C4177'] },
          { id: `${_bookId}_s4`, title: '全职法师', author: '乱世狂刀', coverColors: ['#134E5E', '#71B280'] },
          { id: `${_bookId}_s5`, title: '星际传奇', author: '未来之光', coverColors: ['#6A3093', '#A044FF'] },
          { id: `${_bookId}_s6`, title: '最强医仙', author: '东方一木', coverColors: ['#834D9B', '#D04ED6'] }
        ];
      }, 700);
    },
    // eslint-disable-next-line no-unused-vars
    fetchComments(_bookId) {
      setTimeout(() => {
        this.comments = [
          {
            id: 1,
            username: '阅读爱好者',
            avatarColors: ['#4DA0B0', '#D39D38'],
            rating: 5,
            content: '这本书情节紧凑，人物刻画生动，主角成长历程很有代入感，推荐给喜欢修真题材的读者。',
            time: '2023-03-01 14:30',
            likes: 45,
            liked: false
          },
          {
            id: 2,
            username: '飘渺云烟',
            avatarColors: ['#5614B0', '#DBD65C'],
            rating: 4,
            content: '世界观设定很有特色，但中间情节稍有拖沓，期待后续发展。',
            time: '2023-02-28 09:15',
            likes: 23,
            liked: false
          },
          {
            id: 3,
            username: '书海漫游',
            avatarColors: ['#2A5470', '#4C4177'],
            rating: 4.5,
            content: '作者的文笔很有特点，描写细腻，能够带给读者很强的画面感。主角的成长轨迹也很合理，不像有些小说那样开挂无敌。',
            time: '2023-02-25 21:44',
            likes: 67,
            liked: false
          },
          {
            id: 4,
            username: '夜读书虫',
            avatarColors: ['#134E5E', '#71B280'],
            rating: 5,
            content: '追了两年的书，每一章都很精彩，作者更新也很稳定，是不可多得的佳作！',
            time: '2023-02-20 18:30',
            likes: 89,
            liked: false
          },
          {
            id: 5,
            username: '幻想之旅',
            avatarColors: ['#6A3093', '#A044FF'],
            rating: 3.5,
            content: '前期很精彩，中期有些拖沓，希望后期能够回归正轨。总体来说还是值得一读的作品。',
            time: '2023-02-15 11:22',
            likes: 34,
            liked: false
          }
        ];
      }, 800);
    },
    startReading() {
      this.$router.push(`/reader/${this.book.id}`);
    },
    addToBookshelf() {
      this.$message({
        message: '已加入书架！',
        type: 'success'
      });
    },
    toggleFavorite() {
      this.isFavorite = !this.isFavorite;
      this.$message({
        message: this.isFavorite ? '已收藏！' : '已取消收藏',
        type: 'success'
      });
    },
    handleChapterPageChange(page) {
      this.currentChapterPage = page;
    },
    toggleChapterOrder() {
      this.chapterOrder = this.chapterOrder === 'asc' ? 'desc' : 'asc';
      this.currentChapterPage = 1;
    },
    submitComment() {
      if (!this.userComment.trim()) {
        this.$message.warning('评论内容不能为空');
        return;
      }
      
      const newComment = {
        id: this.comments.length + 1,
        username: '当前用户',
        avatarColors: ['#00416A', '#E4E5E6'],
        rating: this.userRating,
        content: this.userComment,
        time: new Date().toLocaleString(),
        likes: 0,
        liked: false
      };
      
      this.comments.unshift(newComment);
      
      this.userComment = '';
      this.userRating = 0;
      
      this.$message.success('评论发布成功');
    },
    likeComment(index) {
      if (index < 0 || index >= this.comments.length) return;
      
      const comment = this.comments[index];
      if (comment.liked) {
        comment.likes--;
        comment.liked = false;
      } else {
        comment.likes++;
        comment.liked = true;
      }
    },
    replyComment(index) {
      if (index < 0 || index >= this.comments.length) return;
      
      const username = this.comments[index].username;
      this.userComment = `@${username} `;
      this.$nextTick(() => {
        document.querySelector('.comment-form-wrapper').scrollIntoView({ behavior: 'smooth' });
      });
    },
    loadMoreComments() {
      this.displayCommentCount = this.comments.length;
    },
    collapseComments() {
      this.displayCommentCount = 3;
      // 滚动到评论区顶部
      this.$nextTick(() => {
        document.querySelector('.comments-section').scrollIntoView({ behavior: 'smooth' });
      });
    },
    handleJumpPage() {
      if (!this.jumpPage) return;
      
      let page = parseInt(this.jumpPage);
      
      // 确保页码在有效范围内
      if (isNaN(page) || page < 1) {
        page = 1;
      } else if (page > this.totalPages) {
        page = this.totalPages;
      }
      
      this.currentChapterPage = page;
      this.jumpPage = '';
    }
  }
}
</script>

<style scoped>
.book-header {
  background-color: #f5f7fa;
  padding: 40px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

.book-info-wrapper {
  display: flex;
  gap: 30px;
}

.book-cover {
  flex: 0 0 200px;
  height: 266px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.book-cover-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  text-shadow: 0 1px 3px rgba(0,0,0,0.3);
  font-weight: bold;
  font-size: 24px;
  text-align: center;
  padding: 20px;
}

.book-cover-title {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.book-info {
  flex: 1;
}

.book-title {
  font-size: 24px;
  margin: 0 0 10px;
  color: #333;
}

.book-meta {
  margin-bottom: 15px;
  font-size: 14px;
  color: #666;
}

.book-rating {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.rating-score {
  font-size: 24px;
  color: #ff9900;
  margin-right: 10px;
  font-weight: bold;
}

.rating-count {
  font-size: 14px;
  color: #999;
  margin-left: 10px;
}

.author-link {
  color: #409EFF;
  text-decoration: none;
}

.separator {
  margin: 0 8px;
}

.status {
  padding: 2px 6px;
  background-color: #e6f7ff;
  color: #1890ff;
  border-radius: 4px;
  font-size: 12px;
}

.status.completed {
  background-color: #f6ffed;
  color: #52c41a;
}

.book-stats {
  display: flex;
  margin: 15px 0;
}

.stat-item {
  margin-right: 20px;
  text-align: center;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.book-desc {
  margin: 15px 0;
  line-height: 1.6;
  color: #666;
}

.book-tags {
  margin: 15px 0;
}

.book-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.book-actions {
  margin: 20px 0;
}

.last-updated {
  font-size: 14px;
  color: #999;
}

.update-time {
  color: #666;
}

.book-content {
  padding: 40px 15px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.section-title {
  font-size: 20px;
  margin: 0;
  color: #333;
}

.chapter-list {
  margin-bottom: 20px;
}

.chapter-item {
  display: block;
  padding: 10px 15px;
  background-color: #f9f9f9;
  margin-bottom: 10px;
  border-radius: 4px;
  color: #333;
  text-decoration: none;
  transition: all 0.3s;
}

.chapter-item:hover {
  background-color: #e6f7ff;
  color: #1890ff;
}

.pagination-wrapper {
  text-align: center;
  margin-top: 20px;
}

.comments-section {
  margin-top: 40px;
}

.comments-count {
  font-size: 14px;
  color: #999;
}

.comment-form-wrapper {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.user-rating {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.rating-label {
  margin-right: 10px;
  color: #666;
}

.form-actions {
  margin-top: 15px;
  text-align: right;
}

.comments-list {
  margin-top: 30px;
}

.comment-item {
  border-bottom: 1px solid #eee;
  padding: 20px 0;
}

.comment-user {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-weight: bold;
  margin-right: 15px;
}

.username {
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.comment-content {
  line-height: 1.6;
  color: #333;
  margin-bottom: 15px;
}

.comment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #999;
  font-size: 14px;
}

.comment-time {
  color: #999;
}

.comment-actions {
  display: flex;
}

.view-more-comments {
  text-align: center;
  margin-top: 20px;
}

.similar-books-section {
  margin-top: 40px;
}

.book-item {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.book-item:hover {
  transform: translateY(-5px);
}

.book-cover-wrapper {
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.mt-1 {
  margin-top: 5px;
}

.mt-2 {
  margin-top: 10px;
}

.mt-3 {
  margin-top: 15px;
}

.mt-4 {
  margin-top: 20px;
}

.mt-5 {
  margin-top: 40px;
}

.mb-4 {
  margin-bottom: 20px;
}

.mb-5 {
  margin-bottom: 40px;
}

.text-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.text-secondary {
  color: #999;
  font-size: 14px;
}

.chapter-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.order-buttons {
  white-space: nowrap;
}

.jump-page-input {
  width: 120px;
}

@media (max-width: 768px) {
  .book-info-wrapper {
    flex-direction: column;
  }
  
  .book-cover {
    margin: 0 auto 20px;
  }
  
  .book-info {
    width: 100%;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .chapter-controls {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    margin-top: 10px;
  }
  
  .jump-page-input {
    width: 100%;
    margin-top: 10px;
  }
  
  .chapter-item {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style> 